// pages/worldArtCatalog/worldArtCatalog.js
Page({
  data: {
    posts: [],
    loading: false,
    error: null,
    hasMore: true,
    currentPage: 1,
    
    // 发布相关
    showPublish: false,
    publishContent: '',
    publishImages: [],
    publishVideo: '',
    publishing: false,
    
    // 评论相关
    showComments: false,
    
    // 用户信息
    userInfo: null
  },

  onLoad(options) {
    this.loadUserInfo();
    this.testCloudFunction(); // 先测试云函数
    this.loadPosts();
  },

  onShow() {
    // 每次显示页面时刷新帖子列表
    this.loadPosts();
  },

  // 测试云函数
  async testCloudFunction() {
    try {
      console.log('开始测试云函数...');
      
      const { result } = await wx.cloud.callFunction({
        name: 'testArtPosts',
        data: { test: true }
      });
      
      console.log('测试云函数结果:', result);
      
      if (result && result.success) {
        console.log('✅ 云函数测试成功');
        console.log('openid:', result.openid);
      } else {
        console.error('❌ 云函数测试失败:', result);
        wx.showToast({
          title: '云函数测试失败',
          icon: 'none'
        });
      }
    } catch (error) {
      console.error('❌ 云函数测试异常:', error);
      wx.showToast({
        title: '云函数连接失败',
        icon: 'none'
      });
    }
  },

  // 加载用户信息
  async loadUserInfo() {
    try {
      const userInfo = wx.getStorageSync('userInfo');
      if (userInfo) {
        this.setData({ userInfo });
      }
    } catch (error) {
      console.error('加载用户信息失败:', error);
    }
  },

  // 加载帖子列表
  async loadPosts() {
    this.setData({ loading: true, error: null });
    
    try {
      console.log('开始调用云函数获取帖子...');
      
      const { result } = await wx.cloud.callFunction({
        name: 'createArtPosts',
        data: {
          action: 'getPosts',
          data: {
            page: 1,
            pageSize: 10
          }
        }
      });
      
      console.log('云函数返回结果:', result);
      
      if (result && result.success) {
        this.setData({
          posts: result.data || [],
          loading: false,
          currentPage: 1,
          hasMore: result.hasMore
        });
        console.log('帖子加载成功，数量:', result.data?.length || 0);
      } else {
        console.error('云函数返回错误:', result);
        this.setData({
          error: result?.message || '加载失败',
          loading: false
        });
      }
    } catch (err) {
      console.error('加载帖子失败:', err);
      console.error('错误详情:', {
        message: err.message,
        stack: err.stack,
        name: err.name
      });
      this.setData({
        error: '网络错误，请稍后重试',
        loading: false
      });
    }
  },

  // 加载更多
  async loadMore() {
    if (this.data.loading || !this.data.hasMore) return;
    
    this.setData({ loading: true });
    
    try {
      const { result } = await wx.cloud.callFunction({
        name: 'createArtPosts',
        data: {
          action: 'getPosts',
          data: {
            page: this.data.currentPage + 1,
            pageSize: 10
          }
        }
      });
      
      if (result && result.success) {
        this.setData({
          posts: [...this.data.posts, ...(result.data || [])],
          loading: false,
          currentPage: this.data.currentPage + 1,
          hasMore: result.hasMore
        });
      } else {
        this.setData({ loading: false });
      }
    } catch (err) {
      console.error('加载更多失败:', err);
      this.setData({ loading: false });
    }
  },

  // 显示发布弹窗
  showPublishModal() {
    this.setData({ showPublish: true });
  },

  // 隐藏发布弹窗
  hidePublishModal() {
    this.setData({ 
      showPublish: false,
      publishContent: '',
      publishImages: [],
      publishVideo: ''
    });
  },

  // 阻止事件冒泡
  stopPropagation() {
    // 空函数，用于阻止事件冒泡
  },

  // 内容输入
  onContentInput(e) {
    this.setData({ publishContent: e.detail.value });
  },

  // 选择图片
  async chooseImage() {
    try {
      const { tempFilePaths } = await wx.chooseImage({
        count: 9 - this.data.publishImages.length,
        sizeType: ['compressed'],
        sourceType: ['album', 'camera']
      });
      
      this.setData({
        publishImages: [...this.data.publishImages, ...tempFilePaths]
      });
    } catch (error) {
      console.error('选择图片失败:', error);
    }
  },

  // 移除图片
  removeImage(e) {
    const index = e.currentTarget.dataset.index;
    const images = [...this.data.publishImages];
    images.splice(index, 1);
    this.setData({ publishImages: images });
  },

  // 选择视频
  async chooseVideo() {
    try {
      const { tempFilePath } = await wx.chooseVideo({
        sourceType: ['album', 'camera'],
        maxDuration: 60,
        camera: 'back'
      });
      
      this.setData({ publishVideo: tempFilePath });
    } catch (error) {
      console.error('选择视频失败:', error);
    }
  },

  // 移除视频
  removeVideo() {
    this.setData({ publishVideo: '' });
  },

  // 发布帖子
  async publishPost() {
    const { publishContent, publishImages, publishVideo } = this.data;
    
    console.log('开始发布帖子，数据:', {
      content: publishContent,
      imagesCount: publishImages.length,
      hasVideo: !!publishVideo,
      userInfo: this.data.userInfo
    });
    
    if (!publishContent.trim() && publishImages.length === 0 && !publishVideo) {
      wx.showToast({
        title: '请输入内容',
        icon: 'none'
      });
      return;
    }
    
    this.setData({ publishing: true });
    
    try {
      // 上传图片
      let uploadedImages = [];
      if (publishImages.length > 0) {
        console.log('开始上传图片，数量:', publishImages.length);
        
        const uploadPromises = publishImages.map((filePath, index) => {
          const cloudPath = `art-posts/${Date.now()}-${index}-${Math.random().toString(36).substr(2, 9)}.jpg`;
          console.log(`上传图片 ${index + 1}:`, { filePath, cloudPath });
          
          return wx.cloud.uploadFile({
            cloudPath,
            filePath
          });
        });
        
        const uploadResults = await Promise.all(uploadPromises);
        uploadedImages = uploadResults.map(result => result.fileID);
        console.log('图片上传完成:', uploadedImages);
      }
      
      // 上传视频
      let uploadedVideo = '';
      if (publishVideo) {
        console.log('开始上传视频:', publishVideo);
        
        const videoResult = await wx.cloud.uploadFile({
          cloudPath: `art-videos/${Date.now()}-${Math.random().toString(36).substr(2, 9)}.mp4`,
          filePath: publishVideo
        });
        uploadedVideo = videoResult.fileID;
        console.log('视频上传完成:', uploadedVideo);
      }
      
      // 准备发布数据
      const postData = {
        content: publishContent.trim(),
        images: uploadedImages,
        video: uploadedVideo,
        userInfo: this.data.userInfo || {
          nickName: '匿名用户',
          avatarUrl: '/images/default-avatar.png'
        }
      };
      
      console.log('准备发布帖子数据:', postData);
      
      // 发布帖子
      const { result } = await wx.cloud.callFunction({
        name: 'createArtPosts',
        data: {
          action: 'create',
          data: postData
        }
      });
      
      console.log('发布帖子云函数返回:', result);
      
      if (result && result.success) {
        wx.showToast({
          title: '发布成功',
          icon: 'success'
        });
        this.hidePublishModal();
        this.loadPosts(); // 刷新帖子列表
      } else {
        console.error('发布失败，云函数返回:', result);
        wx.showToast({
          title: result?.message || '发布失败',
          icon: 'none',
          duration: 3000
        });
      }
    } catch (error) {
      console.error('发布失败，异常详情:', error);
      console.error('错误堆栈:', error.stack);
      wx.showToast({
        title: '发布失败，请稍后重试',
        icon: 'none',
        duration: 3000
      });
    } finally {
      this.setData({ publishing: false });
    }
  },

  // 点赞/取消点赞
  async toggleLike(e) {
    const { postId, index } = e.currentTarget.dataset;
    const { userInfo } = this.data;
    
    try {
      const { result } = await wx.cloud.callFunction({
        name: 'createArtPosts',
        data: {
          action: 'like',
          data: { 
            postId,
            userInfo: userInfo || {
              nickName: '匿名用户',
              avatarUrl: '/images/default-avatar.png'
            }
          }
        }
      });
      
      if (result && result.success) {
        const posts = [...this.data.posts];
        const post = posts[index];
        post.isLiked = result.isLiked;
        post.likeCount = result.likeCount;
        
        // 更新点赞用户列表
        if (result.likeUsers) {
          post.likeUsers = result.likeUsers;
        } else if (result.isLiked) {
          // 如果是点赞操作，添加当前用户到点赞列表
          post.likeUsers = [...(post.likeUsers || []), {
            nickName: userInfo?.nickName || '匿名用户',
            avatarUrl: userInfo?.avatarUrl || '/images/default-avatar.png'
          }];
        } else {
          // 如果是取消点赞，从点赞列表中移除当前用户
          post.likeUsers = (post.likeUsers || []).filter(user => 
            user.avatarUrl !== (userInfo?.avatarUrl || '/images/default-avatar.png')
          );
        }
        
        this.setData({ posts });
        
        wx.showToast({
          title: result.isLiked ? '点赞成功' : '取消点赞',
          icon: 'success'
        });
      }
    } catch (error) {
      console.error('点赞失败:', error);
      wx.showToast({
        title: '操作失败',
        icon: 'none'
      });
    }
  },

  // 显示评论
  // 切换评论输入框显示
  toggleCommentInput(e) {
    const { postId, index } = e.currentTarget.dataset;
    console.log('切换评论输入框，postId:', postId, 'index:', index);
    
    const posts = [...this.data.posts];
    const post = posts[index];
    
    // 切换当前帖子的评论输入框显示状态
    post.showCommentInput = !post.showCommentInput;
    if (post.showCommentInput) {
      // 如果显示输入框，加载评论
      this.loadCommentsForPost(postId, index);
    }
    
    this.setData({ posts });
  },

  // 加载指定帖子的评论
  async loadCommentsForPost(postId, index) {
    try {
      const { result } = await wx.cloud.callFunction({
        name: 'createArtPosts',
        data: {
          action: 'getComments',
          data: { postId }
        }
      });
      
      if (result && result.success) {
        const posts = [...this.data.posts];
        posts[index].comments = result.data || [];
        this.setData({ posts });
      }
    } catch (error) {
      console.error('加载评论失败:', error);
    }
  },

  // 评论输入
  onCommentInput(e) {
    const { postId, index } = e.currentTarget.dataset;
    const value = e.detail.value;
    console.log('评论输入:', value, 'postId:', postId, 'index:', index);
    
    const posts = [...this.data.posts];
    posts[index].commentContent = value;
    this.setData({ posts });
  },

  // 添加评论
  async addComment(e) {
    const { postId, index } = e.currentTarget.dataset;
    const posts = [...this.data.posts];
    const post = posts[index];
    
    if (!post.commentContent || !post.commentContent.trim()) return;
    
    try {
      const { result } = await wx.cloud.callFunction({
        name: 'createArtPosts',
        data: {
          action: 'comment',
          data: {
            postId: postId,
            content: post.commentContent,
            userInfo: this.data.userInfo || {
              nickName: '匿名用户',
              avatarUrl: '/images/default-avatar.png'
            }
          }
        }
      });
      
      if (result && result.success) {
        // 清空输入框
        post.commentContent = '';
        
        // 重新加载评论列表
        await this.loadCommentsForPost(postId, index);
        
        // 更新帖子评论数
        post.commentCount = (post.commentCount || 0) + 1;
        
        this.setData({ posts });
        
        wx.showToast({
          title: '评论成功',
          icon: 'success'
        });
      }
    } catch (error) {
      console.error('评论失败:', error);
      wx.showToast({
        title: '评论失败',
        icon: 'none'
      });
    }
  },

  // 图片加载成功
  onImageLoad(e) {
    console.log('图片加载成功:', e.detail);
  },
  
  // 图片加载失败
  onImageError(e) {
    console.error('图片加载失败:', e.detail);
    const { src } = e.detail;
    // 替换为默认头像
    if (src && !src.includes('default-avatar.png')) {
      const posts = [...this.data.posts];
      // 更新点赞头像
      posts.forEach(post => {
        if (post.likeUsers) {
          post.likeUsers = post.likeUsers.map(user => {
            if (user.avatarUrl === src) {
              return { ...user, avatarUrl: '/images/default-avatar.png' };
            }
            return user;
          });
        }
        if (post.comments) {
          post.comments = post.comments.map(comment => {
            if (comment.userInfo.avatarUrl === src) {
              return { 
                ...comment, 
                userInfo: { 
                  ...comment.userInfo, 
                  avatarUrl: '/images/default-avatar.png' 
                } 
              };
            }
            return comment;
          });
        }
      });
      this.setData({ posts });
    }
  },
  
  // 预览图片
  previewImage(e) {
    const { urls, current } = e.currentTarget.dataset;
    wx.previewImage({
      urls,
      current
    });
  },

  // 下拉刷新
  onPullDownRefresh() {
    this.loadPosts().finally(() => {
      wx.stopPullDownRefresh();
    });
  },

  // 上拉触底
  onReachBottom() {
    this.loadMore();
  },

  // 分享
  onShareAppMessage() {
    return {
      title: '世界名画图鉴',
      path: '/pages/worldArtCatalog/worldArtCatalog'
    };
  }
});